import Axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type CustomParamsSerializer
} from "axios";
import type {
  PureHttpError,
  RequestMethods,
  PureHttpResponse,
  PureHttpRequestConfig
} from "./types.d";
import { stringify } from "qs";
import NProgress from "../progress";
import { getToken, formatToken } from "@/utils/auth";
import { useUserStoreHook } from "@/store/modules/user";
import { message } from "@/utils/message";
const { VITE_GLOBAL_API_URL } = import.meta.env;

// 相关配置请参考：www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig: AxiosRequestConfig = {
  // 请求超时时间
  timeout: 10000,
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
  // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
  paramsSerializer: {
    serialize: stringify as unknown as CustomParamsSerializer
  }
};

class PureHttp {
  constructor() {
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  /** `token`过期后，暂存待执行的请求 */
  private static requests = [];

  /** 防止重复刷新`token` */
  private static isRefreshing = false;

  /** 初始化配置对象 */
  private static initConfig: PureHttpRequestConfig = {};

  /** 保存当前`Axios`实例对象 */
  public static axiosInstance: AxiosInstance = Axios.create(defaultConfig);

  /** 重连原始请求 */
  private static retryOriginalRequest(config: PureHttpRequestConfig) {
    return new Promise(resolve => {
      PureHttp.requests.push((token: string) => {
        config.headers["Authorization"] = formatToken(token);
        resolve(config);
      });
    });
  }

  /** 请求拦截 */
  private httpInterceptorsRequest(): void {
    PureHttp.axiosInstance.interceptors.request.use(
      async (config: PureHttpRequestConfig): Promise<any> => {

        if (config.url.startsWith("/api")) {
          const apiBase = VITE_GLOBAL_API_URL
          config.url = `${apiBase}${config.url}`
        }

        // 开启进度条动画
        NProgress.start();

        // 优先判断post/get等方法是否传入回调，否则执行初始化设置等回调
        if (typeof config.beforeRequestCallback === "function") {
          config.beforeRequestCallback(config);
          return config;
        }
        if (PureHttp.initConfig.beforeRequestCallback) {
          PureHttp.initConfig.beforeRequestCallback(config);
          return config;
        }
        /** 请求白名单，放置一些不需要`token`的接口（通过设置请求白名单，防止`token`过期后再请求造成的死循环问题） */
        const whiteList = ["/refresh-token", "/login", "/api/token", "/api/token/refresh"];
        return whiteList.some(url => config.url.endsWith(url))
          ? config
          : new Promise(resolve => {
            const data = getToken();
            if (data) {
              const now = new Date().getTime();
              const expired = parseInt(data.expires) - now <= 0;
              if (expired) {//需要跳回登录页
                localStorage.clear(); // 清空 token
                useUserStoreHook().logOut();
              } else {
                config.headers["Authorization"] = formatToken(
                  data.accessToken
                );
                resolve(config);
              }
            } else {
              resolve(config);
            }
          });
      },
      error => {
        return Promise.reject(error);
      }
    );
  }

  /** 响应拦截 */
  private httpInterceptorsResponse(): void {
    const instance = PureHttp.axiosInstance;
    instance.interceptors.response.use(
      (response: PureHttpResponse) => {
        const $config = response.config;
        // 关闭进度条动画
        NProgress.done();
        // 处理响应异常
        if (response.data.code === 200 && response.data.success === false) {
          message(response.data.detail, { type: "error" });
          return Promise.reject(response.data.detail);
        }
        // 优先判断post/get等方法是否传入回调，否则执行初始化设置等回调
        if (typeof $config.beforeResponseCallback === "function") {
          $config.beforeResponseCallback(response);
          return response.data;
        }
        if (PureHttp.initConfig.beforeResponseCallback) {
          PureHttp.initConfig.beforeResponseCallback(response);
          return response.data;
        }
        return response.data;
      },
      (error: PureHttpError) => {
        const $error = error;
        $error.isCancelRequest = Axios.isCancel($error);
        // 关闭进度条动画
        NProgress.done();

        // 处理401错误，自动刷新token
        if ($error.response?.status === 401 && !$error.config?.url?.endsWith('/api/token/refresh')) {
          if (!PureHttp.isRefreshing) {
            PureHttp.isRefreshing = true;
            const tokenData = getToken() as any;
            if (tokenData?.refreshToken) {
              // ✅ 使用 ISO 标准时间格式 或 时间戳
              const expiryTimeIso = new Date(tokenData.refreshTokenExpiryTime || tokenData.expires).toISOString();

              return useUserStoreHook()
                .handRefreshToken({
                  token: tokenData.accessToken,
                  refreshToken: tokenData.refreshToken,
                  refreshTokenExpiryTime: expiryTimeIso // 推荐使用 ISO 字符串
                  // 或使用时间戳：new Date(...).getTime()
                })
                .then(res => {
                  const newAccessToken = res.data.accessToken;
                  // 更新 Authorization 头
                  $error.config.headers['Authorization'] = formatToken(newAccessToken);
                  // 执行等待队列中的回调
                  PureHttp.requests.forEach(cb => cb(newAccessToken));
                  PureHttp.requests = [];
                  // 重试原请求
                  return PureHttp.axiosInstance.request($error.config);
                })
                .catch(() => {
                  // 🔐 刷新失败，执行登出
                  useUserStoreHook().logout(); // 清除状态、跳转登录页等
                  return Promise.reject($error);
                })
                .finally(() => {
                  PureHttp.isRefreshing = false;
                });
            }
          }
          // 当前正在刷新，将请求加入队列等待
          return PureHttp.retryOriginalRequest($error.config);
        }
        if ($error.response?.status === 403) {
          // @ts-ignore
          message($error.response?.data.message, { type: "error" });
          // @ts-ignore
          return Promise.reject($error.response?.data.message);
        }
        if ($error.response?.status === 400 || $error.response?.status === 404) {
          // @ts-ignore
          let msg = $error.response?.data.message ?? $error.message;
          message(msg, { type: "error" });
          // @ts-ignore
          return Promise.reject(msg);
        }
        if ($error.response?.status === 500) {
          // @ts-ignore
          let msg = $error.response?.data.message === undefined ? "服务器异常" : $error.response?.data.message;
          message(msg, { type: "error" });
          // @ts-ignore
          return Promise.reject(msg);
        }
        // 所有的响应异常 区分来源为取消请求/非取消请求
        return Promise.reject($error);
      }
    );
  }

  /** 通用请求工具函数 */
  public request<T>(
    method: RequestMethods,
    url: string,
    param?: AxiosRequestConfig,
    axiosConfig?: PureHttpRequestConfig
  ): Promise<T> {
    const config = {
      method,
      url,
      ...param,
      ...axiosConfig
    } as PureHttpRequestConfig;

    // 单独处理自定义请求/响应回调
    return new Promise((resolve, reject) => {
      PureHttp.axiosInstance
        .request(config)
        .then((response: undefined) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  /** 单独抽离的`post`工具函数 */
  public post<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: PureHttpRequestConfig
  ): Promise<T> {
    return this.request<T>("post", url, params, config);
  }

  /** 单独抽离的`get`工具函数 */
  public get<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: PureHttpRequestConfig
  ): Promise<T> {
    return this.request<T>("get", url, params, config);
  }
}

export const http = new PureHttp();
export default PureHttp.axiosInstance; //新增：适配使用npm run openapi2ts 命令生成的API接口